import axios from 'axios'
import ImageCompressor from 'image-compressor.js';
// console.log(ImageCompressor, 'ImageCompressor')
import {
  showToast
} from 'vant';
import 'vant/es/toast/style';
export const vantUpload = (dataV) => { //其实可以做个压缩的方法 只是波比不想做，以后完善
  return axios({
    method: "post",
    headers: {
      "Content-Type": "multipart/form-data"
    }, //重点--请求头
    url: import.meta.env.VITE_BASE_URL + "/api/common/upload",
    data: dataV,
  });
}
const compressFile = (file) => {
  return new Promise((resolve, reject) => {
    new ImageCompressor(file, {
      quality: 0.6, //压缩质量
      checkOrientation: false, //图片翻转，默认为false
      success(result) {
        const formData = new FormData();
        formData.append('file', result, result.name);
        // Send the compressed image file to server with XMLHttpRequest.
        axios.post(
          import.meta.env.VITE_BASE_URL + "/api/common/upload", formData).then((data) => {
          // console.log(data.data.data)
          resolve(data.data.data);
        });
      },
      error(e) {
        reject()
        showToast('上传图片失败')
      }
    })
  })
}

export const uploadMaterialImg = async (imgFile) => { //这个是封装过的图片压缩方法
  if (imgFile.file.size <= 1024 * 1024) {
    //小于1MB时不压缩直接上传
    return new Promise((resolve, reject) => {
      const formData = new FormData();
      formData.append('file', imgFile.file, imgFile.file.name);
      // Send the compressed image file to server with XMLHttpRequest.
      axios.post(
        import.meta.env.VITE_BASE_URL + "/api/common/upload", formData).then((data) => {
        resolve(data.data.data);
      }).catch(e => {
        reject()
        showToast('上传图片失败')
      });
    })
  } else {
    return compressFile(imgFile.file)
    // return new Promise((resolve, reject) => {
    //   resolve(file)
    // })
  }
}